import requests
import base64


def get_access_token():
    url = 'https://aip.baidubce.com/oauth/2.0/token'
    data = {
        'grant_type': 'client_credentials',
        'client_id': 'IWDyN35bBe2E4KNtfUnQ4GOf',
        'client_secret': 'XYoFYx9QphF0HDG7BkzP6IhTPK7HPObQ'
    }
    res = requests.post(url, data=data)
    res = res.json()

    access_token = res['access_token']        #获取访问令牌
    return access_token                       #百度返回的读取令牌


def photos_loads(save_path):
    request_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime"
    f = open(save_path, 'rb')  # 二进制方式打开图片文件

    img = base64.b64encode(f.read())

    params = {"image": img}
    access_token = '24.11731cd1f0...9f9b3a930f917f3681b.2592000.1596894747.282335-21221990'        #令牌地址
    request_url = request_url + "?access_token=" + get_access_token()
    headers = {'content-type': 'application/x-www-form-urlencoded'}      #返回的类型
    response = requests.post(request_url, data=params, headers=headers)
    res = response.json()          #返回的处理后的数据
    return res
    # 前面我们讲述了这个请求返回的是一个字典，其中一个键就是image，代表的是处理后的图像信息。
    # 将这个图像信息写入，得到最终的效果图。
    # if res:
    #     f = open(save_path, 'wb')
    #     after_img = res['image']
    #     after_img = base64.b64decode(after_img)        #将返回的图像数据解码回图片形式
    #     f.write(after_img)
    #     f.close()

def photos_down(save_path,down_path):
    # photos_loads(save_path)
    img = base64.b64decode(photos_loads(save_path)["image"])
    file = open(down_path, 'wb')
    print(file)
    file.write(img)
    file.close()
    return down_path


